const fs = require('node:fs');
const path = require('node:path');
const readline = require('node:readline');

const directoryPath = 'E:\\迅雷下载\\待处理剧集\\新编十万个为什么\\新编十万个为什么';

const resultPath = 'E:\\迅雷下载\\待处理剧集\\新编十万个为什么\\resultPath';

// const oldFilePath = path.join(directoryPath, file)

const files = fs.readdirSync(directoryPath);
const dirLen = files.length;

let cp_info = [];

files.forEach(async item => {
  const dir = path.join(directoryPath, item);

  const dirFiles = fs.readdirSync(dir);

  const es = await new Promise(resolve => {
    const cfg = dirFiles.find(item => item.includes('entry.json'));

    fs.readFile(dir + '\\' + cfg, 'utf8', (err, data) => {
      const obj = JSON.parse(data);
      resolve(obj.page_data.page);
    });
  });

  const sdir = await new Promise(resolve => {
    const ix = dirFiles.find(item => {
      const stats = fs.statSync(dir + '\\' + item);
      if (stats.isDirectory()) {
        return true;
      }
    });

    resolve(ix);
  });

  const dirFilesx = fs.readdirSync(dir + '\\' + sdir);

  let video = dirFilesx.find(item => item.includes('video.m4s'));
  if (video) {
    video = dir + '\\' + sdir + '\\' + video;
  }

  let audio = dirFilesx.find(item => item.includes('audio.m4s'));
  if (audio) {
    audio = dir + '\\' + sdir + '\\' + audio;
  }

  let blv = dirFilesx.find(item => item.includes('.blv'));
  if (blv) {
    blv = dir + '\\' + sdir + '\\' + blv;
  }

  const info = {
    video,
    audio,
    blv,
    es
  };

  cp_info.push(info);

  if (cp_info.length >= dirLen) {
    copyFileArr(cp_info);
  }
});

function copyFileArr(cp_info) {
  let len = 0;

  cp_info.forEach(item => {
    const e = 'E' + item.es;
    if (item.blv) {
      copyFile(item.blv, resultPath + '//' + e + '.mp4', err => {
        if (err) {
          console.error('复制文件时发生错误:', err);
        } else {
          console.log('文件复制成功！');
        }
      });
    } else {
      copyFile(item.video, resultPath + '//' + e + '-video.mp4', err => {
        if (err) {
          console.error('复制文件时发生错误:', err);
        } else {
          console.log('文件复制成功！');
        }
      });

      copyFile(item.audio, resultPath + '//' + e + '-audio.mp3', err => {
        if (err) {
          console.error('复制文件时发生错误:', err);
        } else {
          console.log('文件复制成功！');
        }
      });
    }

    len++;
  });
}

function copyFile(source, destination, callback) {
  fs.readFile(source, (err, data) => {
    if (err) {
      callback(err);
    } else {
      fs.writeFile(destination, data, err => {
        callback(err);
      });
    }
  });
}
